package com.xiaotao.http.core.request;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Set;

public class HttpRequest {
    private HashMap<String,String> headers = new HashMap<>();
    private HashMap<String,String> parameters = new HashMap<>();
    private Socket socket;
    public String method;
    public String URI;
    public String protocol;
    public String queryString;
    public HttpRequest(Socket socket) throws IOException {
        this.socket = socket;
        parseRequest();
    }

    /**
     * 取HTTP请求方式
     * @return
     */
    public String getMethod() {
        return method;
    }

    /**
     * 取请求的资源路径（以/开头）
     * @return
     */
    public String getURI() {
        return URI;
    }

    /**
     * 取请求协议版本
     * @return
     */
    public String getProtocol() {
        return protocol;
    }

    /**
     * 取请求头
     * @param key
     * @return
     */
    public String getHeader(String key) {
        return headers.get(key);
    }

    /**
     * 取出所有请求头的键
     * @return
     */
    public Set<String> getHeaderKeys() {
        return headers.keySet();
    }

    /**
     * 取表单值
     * @param name 表单字段名
     * @return
     */
    public String getParameter(String name) {
        return this.parameters.get(name);
    }

    /**
     * 取出表单中所有的字段名
     * @return
     */
    public Set<String> getParameterNames() {
        return this.parameters.keySet();
    }

    private void parseRequest () throws IOException {
        parseHeader();
        parseBody();
        parseParameter();
    }

    private void parseHeader() throws IOException  {
        BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        String[] headLine = br.readLine().split(" ");
        // 解析初始行
        method = headLine[0];
        String[] part = headLine[1].split("\\?");
        URI = part.length == 0 ? headLine[1] : part[0];
        queryString = part.length < 2 ? "" : part[1];
        protocol = headLine[2];

        // 解析Header
        String header;
        while ( !(header = br.readLine()).isEmpty() ) {
            String[] split = header.split(":");
            headers.put(split[0], split[1].trim());
        }
    }


    /**
     * 解析表单参数
     * @throws IOException
     */
    private void parseParameter() throws IOException {
        String[] part = queryString.split("&");
        for (String string: part ) {
            String[] split = string.split("=");
            if (split.length != 2) {
                continue;
            }
            this.parameters.put(split[0], split[1]);
        }
    }

    private void parseBody () throws IOException {

    }

}
